package com.headwire.kw.helpers.qxml;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class SimpleXMLParser extends DefaultHandler {
	protected QXElement root = null;
	private QXElement curElem = null;
	
	@Override
	public void characters(char[] arg0, int arg1, int arg2) throws SAXException {
		if(curElem == null) {
			// do nothing
		}
		else {
			String txt = String.copyValueOf(arg0,arg1,arg2).trim();
			if(!txt.equals("")) {
				curElem.addText(txt);
			}
		}
	}

	@Override
	public void endDocument() throws SAXException {
		// nothing
	}

	@Override
	public void endElement(String arg0, String arg1, String arg2)
			throws SAXException {
		// just move out of current element
		curElem = curElem.getParent();
	}

	@Override
	public void startDocument() throws SAXException {
		// nothing
	}

	@Override
	public void startElement(String namespaceURI, String sName, String qName,
			Attributes arg3) throws SAXException {
		
		String elementName = sName;
    	if(elementName.equals(""))
    		elementName = qName;
    	
		if(curElem == null && root == null) {
			root = new QXElement(null,elementName);
			curElem = root;
		}
		else {
			curElem = new QXElement(curElem,elementName);
		}
		
		for(int i = 0; i < arg3.getLength(); i++) {
			curElem.addAttribute(arg3.getQName(i),arg3.getValue(i));
		}
	}

}
